/*
    处理站点信息逻辑
*/
const { sqlQuery } = require('../mysql/index')
let sd = require('silly-datetime');

module.exports = {
    getIP, getVisitNumber, getVisitNumberBetweenDate
}

//获取访问网站的ip并存储
async function getIP(ip) {
    let sql = `insert into site_data(time,ip) values("${sd.format(new Date(), 'YYYY-MM-DD HH:mm:ss')}","${ip}");`
    return new Promise(function (resolve, reject) {
        sqlQuery(sql, data => {
            resolve(data)
        })
    })
}

//统计今日网站访问量
/* 
    访问量包括：
    1.今日具体访问次数；
    2.今日具体访问人数；（每个ip只计一次）
*/
async function getVisitNumber(date) {
    let start_time = date + ' 00:00:00';
    let end_time = date + ' 23:59:59';
    let sql = `select * from site_data where time between "${start_time}" and "${end_time}";`
    return new Promise(function (resolve, reject) {
        sqlQuery(sql, data => {
            let result = {
                time: '',//上一条数据的更新时间
                visitNumber: 0,//具体访问次数
                ipNumber: 0//具体访问人数
            }
            let ip = []
            for (let i in data) {
                ip.push(data[i].ip)
                if (i == data.length - 1) {
                    if (i == 0) {
                        result.time = data[i].time
                    }
                    else {
                        result.time = sd.format(data[i - 1].time, 'HH:mm:ss')
                    }
                    result.visitNumber = data.length
                    result.ipNumber = Array.from(new Set(ip)).length;
                    resolve(result)
                }
            }
        })
    })

}

//统计某日访问量
/* 
    参数：count 0--当日，-1--昨日，-2--2天前，-3--3天前......以此推类
*/
async function getVisitNumberByDate(count) {
    let sql = `SELECT * FROM site_data WHERE DATEDIFF(time,NOW())=${count};`
    return new Promise(function (resolve, reject) {
        sqlQuery(sql, data => {
            let result = {
                day: -count,
                visitNumber: 0,//具体访问次数
                ipNumber: 0//具体访问人数
            }
            let ip = []
            if (data[0] == null) {
                resolve(result)
            }
            for (let i in data) {
                ip.push(data[i].ip)
                if (i == data.length - 1) {
                    result.visitNumber = data.length
                    result.ipNumber = Array.from(new Set(ip)).length;
                    resolve(result)
                }
            }
        })
    })
}

//获取连续n天的访问量
async function getVisitNumberBetweenDate(n) {
    let result = []
    for (let i = 0; i <= n; i++) {
        await getVisitNumberByDate(-i).then(res => { result.push(res) })
    }
    return result
}